package com.chainyoung.component_tmperson.ui.activity.financing;

import android.content.Intent;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;


import com.chainyoung.common.appcommon.entity.CommonList;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.common_widget.loadsir.callback.Callback;
import com.chainyoung.common.common_widget.loadsir.core.LoadService;
import com.chainyoung.common.common_widget.loadsir.core.LoadSir;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.custom_widget.EmptyCallback;
import com.chainyoung.common.custom_widget.LoadingCallback;
import com.chainyoung.common.custom_widget.RetryCallback;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.entity.WalletFinancing;
import com.chainyoung.component_tmperson.entity.WalletFinancingOwn;
import com.chainyoung.component_tmperson.entity.WalletProfiRecord;
import com.chainyoung.component_tmperson.ui.adapter.WalletFianancingProfitAdapter;
import com.chainyoung.component_tmperson.ui.mvp.contract.WalletFinancingProfitContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.WalletFinancingProfitPresenter;
import com.chainyoung.component_tmperson.ui.view.WalletFinancingTurnOutDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.simple.eventbus.Subscriber;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;


public class WalletFinancingProfitActivity extends BaseActivity<WalletFinancingProfitPresenter> implements WalletFinancingProfitContract.View {


    @BindView(R2.id.iv_back)
    ImageView ivBack;
    @BindView(R2.id.rb_activie)
    RadioButton rbActivie;
    @BindView(R2.id.rb_fixed)
    RadioButton rbFixed;
    @BindView(R2.id.tv_coin_type)
    TextView tvCoinType;
    @BindView(R2.id.iv_eye)
    ImageView ivEye;
    @BindView(R2.id.tv_profit_amount)
    TextView tvProfitAmount;
    @BindView(R2.id.tv_available_amount)
    TextView tvAvailableAmount;
    @BindView(R2.id.tv_frozen_amount)
    TextView tvFrozenAmount;
    @BindView(R2.id.ll_finacing_profit_top)
    LinearLayout llFinacingProfitTop;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.ll_turn_in)
    LinearLayout llTurnIn;
    @BindView(R2.id.ll_turn_out)
    LinearLayout llTurnOut;
    @BindView(R2.id.rg)
    RadioGroup rg;
    @BindView(R2.id.tv_total_amount)
    TextView tvTotalAmount;
    @BindView(R2.id.ll_top_bottom)
    LinearLayout llTopBottom;

    private final static String TYPE_ACTIVE = "current";//活期
    private final static String TYPE_FIXED = "fixed";//定期

    private WalletFinancing data;
    private WalletFinancingOwn own;
    private String type = TYPE_ACTIVE;

    private WalletFianancingProfitAdapter mAdapter;


    private List<WalletProfiRecord> mData = new ArrayList<>();
    private boolean isCanloadMore;
    protected int pageNo = 1;

    private LoadService loadService;


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected boolean useDefaultStatusBar() {
        return false;
    }


    @Override
    protected void initUI() {
        data = (WalletFinancing) getIntent().getSerializableExtra("walletFinancing");
        type = getIntent().getStringExtra("type");
        if (TextUtils.isEmpty(type)) {
            type = TYPE_ACTIVE;
        }
        switch (type) {
            case TYPE_ACTIVE:
                rbActivie.setChecked(true);
                break;
            case TYPE_FIXED:
                rbFixed.setChecked(true);
                break;
        }
        setTopView();
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_activie) {
                    type = TYPE_ACTIVE;
                    setTopView();
                } else {
                    type = TYPE_FIXED;
                    setTopView();
                }
                getUserTotalProfit();
                pageNo = 1;
                getProfitList();
            }
        });

        initLoadSir();
        initRecylerView();
    }


    private void setTopView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(type.equals(TYPE_ACTIVE) ? ContextCompat.getColor(mContext, R.color._061c69) : ContextCompat.getColor(mContext, R.color._5B1A74));
        }
        switch (type) {
            case TYPE_ACTIVE:
                llFinacingProfitTop.setBackgroundResource(R.mipmap.ic_financing_profit_active_bg);
                tvCoinType.setTextColor(ContextCompat.getColor(mContext, R.color._AFAEFF));
                tvTotalAmount.setTextColor(ContextCompat.getColor(mContext, R.color._AFAEFF));
                llTopBottom.setVisibility(View.INVISIBLE);
                break;
            case TYPE_FIXED:
                llFinacingProfitTop.setBackgroundResource(R.mipmap.ic_financing_profit_fixed_bg);
                tvCoinType.setTextColor(ContextCompat.getColor(mContext, R.color._D884FF));
                tvTotalAmount.setTextColor(ContextCompat.getColor(mContext, R.color._D884FF));
                llTopBottom.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void initLoadSir() {
        LoadSir loadSir = new LoadSir.Builder()
                .addCallback(new LoadingCallback())
                .addCallback(new EmptyCallback())
                .addCallback(new RetryCallback())
                .setDefaultCallback(LoadingCallback.class)
                .build();
        loadService = loadSir.register(refreshLayout, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadService.showCallback(LoadingCallback.class);
                pageNo = 1;
                getProfitList();
            }
        });
    }

    private void initRecylerView() {
        rvList.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new WalletFianancingProfitAdapter(mData);
        rvList.setAdapter(mAdapter);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_divider_gray));
        rvList.addItemDecoration(itemDecoration);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                getProfitList();
            }
        });

        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isCanloadMore) {
                    pageNo++;
                    getProfitList();
                } else {
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                getProfitList();
                getUserTotalProfit();
            }
        });
    }

    @Override
    protected void initData() {
        getUserTotalProfit();
        pageNo = 1;
        getProfitList();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_activity_financing_profit;
    }

    @OnClick(R2.id.iv_back)
    void onFinish() {
        finish();
    }

    @OnClick(R2.id.ll_turn_in)
    void turnIn() {
        if (own == null) {
            return;
        }
        Intent intent = new Intent(mContext, WalletFinancingTradeActivity.class);
        intent.putExtra("walletFinancing", data);
        intent.putExtra("type", type);
        mContext.startActivity(intent);

    }

    @OnClick(R2.id.ll_turn_out)
    void turnOut() {
        if (own == null) {
            return;
        }
        String canTurnOutNum = type.equals(TYPE_ACTIVE) ? own.getCurrent_sum().setScale(8, RoundingMode.DOWN).toPlainString() : own.getFixed_can_turnout_num().setScale(8, RoundingMode.DOWN).toPlainString();
        if (Double.valueOf(canTurnOutNum) == 0) {
            ToastUtil.showToast("暂无可转出数量");
            return;
        }
        WalletFinancingTurnOutDialog dialog = new WalletFinancingTurnOutDialog(mContext, canTurnOutNum);
        dialog.setConfirmListener(new WalletFinancingTurnOutDialog.ConfirmTurnOutListener() {
            @Override
            public void onConfirmTurnOut(String buyNum) {
                turnOutProfit(buyNum);
            }
        });
        dialog.show();

    }


    private void setViews() {
        tvCoinType.setText("已增益(" + data.getName().toUpperCase() + ")");
        switch (type) {
            case TYPE_ACTIVE:
                tvProfitAmount.setText(StringUtil.subZeroAndDot(String.valueOf(own.getTotal_current_profit())));
                tvTotalAmount.setText("总额：" + own.getCurrent_sum().stripTrailingZeros().toPlainString() + "\n" + "≈CNY " +
                        own.getCurrent_sum_cny().setScale(2, RoundingMode.DOWN).stripTrailingZeros().toPlainString());
                break;
            case TYPE_FIXED:
                tvProfitAmount.setText(own.getTotal_fixed_profit().stripTrailingZeros().toPlainString());
                tvTotalAmount.setText("总额：" + own.getFixed_sum().stripTrailingZeros().toPlainString() + "\n" + "≈CNY " +
                        own.getFixed_sum_cny().setScale(2, RoundingMode.DOWN).stripTrailingZeros().toPlainString());
                tvAvailableAmount.setText(own.getFixed_can_turnout_num().stripTrailingZeros().toPlainString());
                tvFrozenAmount.setText(own.getFixed_lock_num().stripTrailingZeros().toPlainString());
                break;
        }
    }


    private void getUserTotalProfit() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put(LibConstant.TOKEN, SPUtil.getString(LibConstant.TOKEN));
        map.put("coin", data.getName());
        mPresenter.getUserFinancingProfit(map);
    }

    private void getProfitList() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put(LibConstant.TOKEN, SPUtil.getString(LibConstant.TOKEN));
        map.put("coin", data.getName());
        map.put("profit_type", type);
        map.put("page", pageNo);
        map.put("limit", LibConstant.PAGE_SIZ);
        mPresenter.getFinancingProfitList(map);
    }

    private void turnOutProfit(String num) {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put(LibConstant.TOKEN, SPUtil.getString(LibConstant.TOKEN));
        map.put("coin", data.getName());
        map.put("profit_type", type);
        map.put("num", num);
        mPresenter.turnOut(map);
    }


    @Override
    public void onGetUserFinancingProfitSuccess(WalletFinancingOwn data) {
        own = data;
        setViews();
    }

    @Override
    public void onGetUserFinancingProfitFailed() {

    }

    @Override
    public void onTurnOutSuccess(String data) {
        ToastUtil.showToast(data);
        getUserTotalProfit();
        pageNo = 1;
        getProfitList();
    }

    @Override
    public void onGetFinancingProfitListSuccess(CommonList<WalletProfiRecord> data) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (pageNo == 1) {
            mData.clear();
        }
        if (data == null) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
            if (pageNo == 1) {
                loadService.showCallback(EmptyCallback.class);
            }
            return;
        }
        mData.addAll(data.getList());
        if (data.getList().size() < LibConstant.PAGE_SIZ) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
        } else {
            isCanloadMore = true;
            refreshLayout.setEnableLoadMore(true);
        }
        mAdapter.notifyDataSetChanged();
        if (mData.isEmpty()) {
            loadService.showCallback(EmptyCallback.class);
        } else {
            loadService.showSuccess();

        }


    }

    @Override
    public void onGetFinancingProfitListFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        loadService.showCallback(RetryCallback.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }


    @Subscriber
    public void onRefresh(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.REFRESH_FINANCING_TRADE) {
            type = (String) event.getData();
            setTopView();
            initData();
        }
    }


}
